package com.p2p.base.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.alibaba.fastjson.JSONObject;
import com.p2p.base.model.BackendUser;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.Module;
import com.p2p.base.model.Oplog;
import com.p2p.base.util.LoginUtil;

/**
 * @author ruiqi
 *
 */
public class BaseController {

	private final Logger logger = LoggerFactory.getLogger(BaseController.class);

	protected BaseUser getCurrentBaseUser() {
		return (BaseUser) LoginUtil.getCurrentUser();
	}

	protected BaseUser getCurrentUser() {
		return getCurrentBaseUser();
	}

	/**
	 * ip,referfer,time,uid已经设置
	 */
	protected Oplog oplog(HttpServletRequest request) {
		Oplog oplog = new Oplog();
		oplog.setIp(getRemoteIp(request));
		oplog.setReferer(request.getHeader("referer"));
		oplog.setTime(new Date());
		Object currentUser = LoginUtil.getCurrentUser();
		if (currentUser instanceof BackendUser) {
			oplog.setUid(((BackendUser) currentUser).getId());
		} else if (currentUser instanceof BaseUser) {
			oplog.setUid(((BaseUser) currentUser).getLongId());
		}
		return oplog;
	}

	public String getRemoteIp(HttpServletRequest request) {
		String remoteIp = request.getHeader("x-forwarded-for");
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("X-Real-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("Proxy-Client-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("HTTP_CLIENT_IP");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteAddr();
		}
		if (remoteIp == null || remoteIp.isEmpty()
				|| "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteHost();
		}
		if (remoteIp != null && remoteIp.indexOf(",") != -1) {
			remoteIp = remoteIp.substring(remoteIp.lastIndexOf(",") + 1,
					remoteIp.length()).trim();
		}
		return remoteIp;
	}

	public void returnJsonObject(HttpServletResponse response, Object bean) {
		String jsonStr = JSONObject.toJSONString(bean);
		returnMessage(response, jsonStr);
	}

	public void returnJsonObject(HttpServletResponse response,
			JSONObject jsonObject) {
		returnMessage(response, jsonObject.toJSONString());
	}

	/**
	 *
	 * @param content
	 */
	public void returnMessage(HttpServletResponse response, String content) {
		// response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			pWriter.write(content);
		} catch (IOException e) {
			logger.error("", e);
		} finally {
			if (pWriter != null) {
				pWriter.flush();
				pWriter.close();
			}
		}
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) throws ServletException {

		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		fmt.setLenient(false);

		CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
		binder.registerCustomEditor(Date.class, dateEditor);

		CustomCollectionEditor collectionEditor = new CustomCollectionEditor(
				List.class, true);

		binder.registerCustomEditor(List.class, collectionEditor);
	}
}
